// 添加到manifest.json的content_scripts部分
const originalXHRSend = XMLHttpRequest.prototype.send;
const originalFetch = window.fetch;

// 安全地发送消息给扩展
function sendMessageToExtension(message) {
  try {
    chrome.runtime.sendMessage(message, response => {
      if (chrome.runtime.lastError) {
        // 忽略连接错误
        console.log('扩展通信错误:', chrome.runtime.lastError.message);
      }
    });
  } catch (error) {
    // 如果扩展上下文失效，忽略错误
    console.log('扩展上下文可能已失效:', error);
  }
}

// 修改 XHR open 方法，确保在 send 之前正确保存 URL
const originalXHROpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url, ...rest) {
  // 保存完整 URL 到 XHR 对象上
  this._method = method.toUpperCase();
  
  // 处理相对路径的 URL
  if (url.startsWith('/') || !url.startsWith('http')) {
    const base = window.location.origin;
    this._url = url.startsWith('/') ? base + url : base + '/' + url;
  } else {
    this._url = url;
  }
  
  // 记录日志，帮助调试
  console.debug('XHR 请求:', this._method, this._url);
  
  return originalXHROpen.apply(this, [method, url, ...rest]);
};

// 修改 XHR send 方法，确保能够捕获请求体
XMLHttpRequest.prototype.send = function(...args) {
  const xhr = this;
  const method = xhr._method || 'GET';
  
  // 只处理 POST 请求
  if (method === 'POST') {
    const originalOnReadyStateChange = xhr.onreadystatechange;
    
    // 增强请求体捕获逻辑
    let requestBody = '';
    if (args.length > 0 && args[0]) {
      requestBody = args[0];
      
      try {
        // 处理不同类型的请求体
        if (typeof requestBody === 'string') {
          try {
            // 尝试格式化 JSON
            const jsonData = JSON.parse(requestBody);
            requestBody = JSON.stringify(jsonData, null, 2);
          } catch (e) {
            // 不是 JSON，保持原样
          }
        } else if (requestBody instanceof FormData) {
          requestBody = '[FormData 对象 - 无法显示详细内容]';
        } else if (requestBody instanceof Blob || requestBody instanceof ArrayBuffer) {
          requestBody = `[${requestBody.constructor.name} - 大小: ${requestBody.size || '未知'}]`;
        } else if (requestBody) {
          // 尝试使用 JSON.stringify 处理其他类型
          try {
            requestBody = JSON.stringify(requestBody);
          } catch (e) {
            requestBody = `[${requestBody.constructor.name || typeof requestBody}]`;
          }
        }
      } catch (e) {
        console.error('处理请求体时出错:', e);
        requestBody = `[错误: ${e.message}]`;
      }
      
      // 立即发送请求体数据，确保 _url 存在
      if (xhr._url) {
        console.debug('发送请求体数据:', xhr._url, requestBody);
        sendMessageToExtension({
          type: 'captureRequest',
          url: xhr._url,
          requestBody: requestBody || '空请求体'
        });
      }
    }
  }
  
  return originalXHRSend.apply(this, args);
};

// 拦截fetch
window.fetch = async function(resource, init = {}) {
  const method = init.method ? init.method.toUpperCase() : 'GET';
  const url = typeof resource === 'string' ? resource : resource.url;
  
  // 捕获请求体
  if (method === 'POST' && init.body) {
    let requestBody = init.body;
    try {
      // 如果是FormData或Blob，尝试转换
      if (requestBody instanceof FormData || requestBody instanceof Blob) {
        // 这里处理比较复杂，暂时记录类型
        requestBody = `[${requestBody.constructor.name}]`;
      } else if (typeof requestBody === 'string') {
        // 尝试解析JSON
        const jsonData = JSON.parse(requestBody);
        requestBody = JSON.stringify(jsonData, null, 2);
      }
    } catch (e) {
      // 保持原样
    }
    
    // 发送请求体数据
    sendMessageToExtension({
      type: 'captureRequest',
      url: url,
      requestBody: requestBody
    });
  }
  
  if (method === 'POST') {
    try {
      const response = await originalFetch.apply(this, [resource, init]);
      const clonedResponse = response.clone();
      
      // 读取响应体
      clonedResponse.text().then(text => {
        let responseBody = text;
        try {
          const jsonData = JSON.parse(text);
          responseBody = JSON.stringify(jsonData, null, 2);
        } catch (e) {
          // 不是JSON，保持原样
        }
        
        // 发送响应体数据（延迟以确保记录已创建）
        setTimeout(() => {
          sendMessageToExtension({
            type: 'captureResponse',
            url: url,
            responseBody: responseBody
          });
        }, 100);
      });
      
      return response;
    } catch (error) {
      throw error;
    }
  }
  
  return originalFetch.apply(this, [resource, init]);
}; 